package cn.donting.fx.ui;

import javafx.beans.property.FloatProperty;
import javafx.beans.property.FloatPropertyBase;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.AccessibleRole;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;

import java.math.BigDecimal;
import java.util.function.UnaryOperator;


public class NumberField extends TextField {
    private float step = 0.1f;


    public final FloatProperty floatProperty;


    public NumberField() {
        super("0");
        NumberField numberField = this;
        floatProperty = new FloatPropertyBase() {
            @Override
            public Object getBean() {
                return NumberField.this;
            }

            @Override
            public String getName() {
                return "";
            }
        };
        textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                try {
                    if (newValue.equals("")) {
                        numberField.setText("0");
                        return;
                    }
                    if (newValue.startsWith(".")) {
                        numberField.setText("0" + newValue);
                    }
                    floatProperty.setValue(new BigDecimal(newValue));
                } catch (Exception e) {
                    numberField.setText(oldValue);
                }
            }
        });
        setOnScroll(new EventHandler<ScrollEvent>() {
            @Override
            public void handle(ScrollEvent event) {
                if (event.getDeltaY() > 0) {
                    setValue(getBigDecimal().add(new BigDecimal(step + "")));
                } else {
                    setValue(getBigDecimal().subtract(new BigDecimal(step + "")));
                }
            }
        });
    }

    public float getFloat() {
        return floatProperty.floatValue();
    }

    public BigDecimal getBigDecimal() {
        return new BigDecimal(getText());
    }

    public void setValue(float value) {
        setText(value + "");
    }

    public void setValue(BigDecimal value) {
        setText(value.toString());
    }
}
